package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class UserServiceImpl implements UserService {
    public final String APPID = "appid";
    public final String SECRET = "secret";
    public final String JS_CODE = "js_code";
    public final String GRANT_TYPE = "grant_type";
    public final String AUTHORIZATION_CODE="authorization_code";
    public final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User login(UserLoginDTO dto) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put(APPID, weChatProperties.getAppid());
        paramMap.put(SECRET, weChatProperties.getSecret());
        paramMap.put(JS_CODE, dto.getCode());
        paramMap.put(GRANT_TYPE, AUTHORIZATION_CODE);
        String result = HttpClientUtil.doGet(WX_LOGIN_URL, paramMap);
        log.info("result = " + result);
        //获取到result之后，判断用户是否存在,使用JSON解析获取Json对象
        JSONObject jsonResult = JSON.parseObject(result);
        String openid = (String) jsonResult.get("openid");
        log.info("openid = {}", openid);
        User user = userMapper.queryByOpenid(openid);
        if (user == null) {
            user = User.builder().openid(openid)
                    .name(openid.substring(3, 6))
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);
        }
        log.info("用户: {}", user);
        return user;
    }
}
